public without sharing class MergeOpportunityController {

    
    public Opportunity opp{get;set;}
    public boolean isShow{get;set;}
    public List<Bean> beanlist{get;set;}

    public String accid='';


    
    /**
     * 封装一个Bean方法，方便在页面添加Checkbox
     * 
     * */    
    public class Bean{
        public Opportunity opp{get;set;}
        public boolean checkbox{get;set;}
        public String cdate{get;set;}

        public Bean(Opportunity record){
            cdate = record.CreatedDate.format();
            opp = record;
            checkbox = false;
        }
        
    }
    
    public MergeOpportunityController(ApexPages.StandardController con){
        opp = new Opportunity();     
        isShow = true;
        accid = System.currentPageReference().getParameters().get('accid');
     
        if (String.isBlank(accid)) {
            ApexPages.addMessage(new ApexPages.Message (ApexPages.Severity.ERROR,'非法的访问路径'));
            isShow = false;
        }else{
            query();
        }

    }

    public void query() {
        beanlist = new List<Bean>();        
        //根据需求，检索此客户下业务机会状态为‘意向’，‘立项’，‘方案谈判’的业务机会
        for ( Opportunity opps : [select id,OwnerId,name,Is_Stop__c,SucceedOpportunity__r.name, CreatedBy.LastName,CreatedDate from Opportunity where AccountId = :accid and Stagename in ('意向','立项','方案谈判','招标') and Is_Stop__c = false and OwnerId = :UserInfo.getUserId()]){
            //if (opps.OwnerId == UserInfo.getUserId()) {
                beanlist.add(new Bean(opps));  
            //}             
        }       
    }
    /**
     * 点击下一页获取所选择业务机会ID，并判断是否选择一个以上、4个以下业务机会进行合并。
     * 
     * */
    public PageReference next() {
      
        Integer num = 1;
        string idstr = '';
        for (Bean ops : beanlist) {
            if (ops.checkbox == true) {
                //oids.add(ops.opp.id);
                idstr += 'id' + num + '=' + ops.opp.id + '&';
                num++;
            }
        }
        idstr = idstr + 'accid'+'='+ accid + '&';

        if ( num != 1 ) {
            idstr = idstr.Substring(0,idstr.Length() - 1);
        } else {
            ApexPages.addMessage(new ApexPages.Message (ApexPages.Severity.ERROR, '请选择至少两个业务机会进行合并'));
        }

        if (num > 4) {
            ApexPages.addMessage(new ApexPages.Message (ApexPages.Severity.ERROR, '一次最多只能选择三个业务机会进行合并'));
            return null;
        } else if ( num < 3 ) {
            ApexPages.addMessage(new ApexPages.Message (ApexPages.Severity.ERROR, '请选择至少两个业务机会进行合并'));
            return null;
        } else {
            return new PageReference( '/apex/MergeOpportunitiesTwo?'+idstr);
        }
    }
    
    public PageReference cancle(){
        return new PageReference('/'+accid);
    }
}